{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "# Pandas 分组统计 - groupby\n",
        "\n",
        "本教程详细介绍如何使用 `groupby()` 进行分组统计操作。\n",
        "\n",
        "## 目录\n",
        "1. groupby() 基础用法\n",
        "2. 单列分组统计\n",
        "3. 多列分组统计\n",
        "4. 聚合函数 - agg()\n",
        "5. 多个统计指标\n",
        "6. 分组过滤和转换\n",
        "7. 综合应用\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 导入库\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "import pandas as pd\n",
        "import numpy as np\n",
        "import warnings\n",
        "warnings.filterwarnings('ignore')\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 1. groupby() 基础用法\n",
        "\n",
        "### 方法说明\n",
        "\n",
        "`groupby()` 用于对数据进行分组，然后对每组进行统计操作。\n",
        "\n",
        "**语法:**\n",
        "```python\n",
        "df.groupby(by=None, axis=0, level=None, as_index=True, sort=True, ...)\n",
        "```\n",
        "\n",
        "**主要参数:**\n",
        "- `by`: 分组依据（列名、函数、字典等）\n",
        "- `axis`: 0(按行分组) 或 1(按列分组)，默认 0\n",
        "- `as_index`: 是否将分组键作为索引，默认 True\n",
        "- `sort`: 是否对分组键排序，默认 True\n",
        "\n",
        "**特点:**\n",
        "- ✅ 支持单列或多列分组\n",
        "- ✅ 可以应用多种聚合函数\n",
        "- ✅ 返回GroupBy对象，需要应用聚合函数\n",
        "\n",
        "**适用场景:** 按类别统计、分组分析、数据汇总\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例1: 创建示例数据\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "np.random.seed(42)\n",
        "df = pd.DataFrame({\n",
        "    '部门': np.random.choice(['技术', '销售', '人事'], 30),\n",
        "    '性别': np.random.choice(['男', '女'], 30),\n",
        "    '年龄': np.random.randint(20, 50, 30),\n",
        "    '工资': np.random.normal(8000, 2000, 30),\n",
        "    '奖金': np.random.normal(2000, 500, 30)\n",
        "})\n",
        "\n",
        "print(\"原始数据 (前10行):\")\n",
        "print(df.head(10))\n",
        "print(\"\\n数据形状:\", df.shape)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 2. 单列分组统计\n",
        "\n",
        "### 示例2: 按部门分组统计平均值\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 按部门分组，计算平均工资\n",
        "print(\"各部门平均工资:\")\n",
        "print(df.groupby('部门')['工资'].mean())\n",
        "print(\"\\n各部门平均年龄:\")\n",
        "print(df.groupby('部门')['年龄'].mean())\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### 示例3: 多个统计指标\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 按部门分组，计算多个统计指标\n",
        "dept_stats = df.groupby('部门')['工资'].agg(['count', 'mean', 'median', 'std', 'min', 'max'])\n",
        "print(\"各部门工资统计:\")\n",
        "print(dept_stats)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 3. 多列分组统计\n",
        "\n",
        "### 示例4: 按部门和性别分组\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 按部门和性别分组，计算平均工资\n",
        "print(\"各部门、性别平均工资:\")\n",
        "print(df.groupby(['部门', '性别'])['工资'].mean())\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 4. 聚合函数 - agg()\n",
        "\n",
        "### 示例5: 使用agg()应用多个聚合函数\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 对多个列应用多个聚合函数\n",
        "print(\"各部门多列多指标统计:\")\n",
        "print(df.groupby('部门').agg({\n",
        "    '工资': ['mean', 'std', 'min', 'max'],\n",
        "    '年龄': ['mean', 'median'],\n",
        "    '奖金': 'sum'\n",
        "}))\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 5. 综合应用\n",
        "\n",
        "### 示例6: 分组后重置索引\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "# 使用as_index=False或reset_index()重置索引\n",
        "print(\"重置索引后:\")\n",
        "result = df.groupby('部门', as_index=False)['工资'].mean()\n",
        "print(result)\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 总结\n",
        "\n",
        "**分组统计方法总结:**\n",
        "1. ✅ **groupby()**: 分组操作\n",
        "2. ✅ **mean(), sum(), count()等**: 聚合函数\n",
        "3. ✅ **agg()**: 应用多个聚合函数\n",
        "4. ✅ **as_index=False**: 重置索引\n",
        "\n",
        "**最佳实践:**\n",
        "- 使用 `groupby()` 进行分组统计\n",
        "- 使用 `agg()` 应用多个聚合函数\n",
        "- 使用 `as_index=False` 或 `reset_index()` 重置索引\n",
        "- 支持单列和多列分组\n",
        "- 可以应用各种统计函数（mean, sum, count, std等）\n"
      ]
    }
  ],
  "metadata": {
    "language_info": {
      "name": "python"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}
